﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TaskManager
{
    public partial class DailyForm : Form
    {
        public DailyForm()
        {
            InitializeComponent();
        }

        public string Mode = "新建";
        private static string time1, time2; // 用于记录开始时间和结束时间

        // 提交日志信息到服务器
        private void button1_Click(object sender, EventArgs e)
        {
            String content = textBox1.Text;                         // 工作内容
            //String consumed = comboBox_hour.Text;                 // 工作耗时
            String consumed = toHours().ToString();                 // 工作耗时
            if (!showConsume) consumed = ((float)Tool.Sub_minite(endTime.Text, startTime.Text) / 60f) + ""; // 耗时计算
            String dstatus = comboBox1.SelectedIndex == 0 ? "3" : "0";      // 进行中对应任务状态"3"

            string html = "";
            if (Mode.Equals("新建")) html = addDaily(content, startTime.Text, consumed, endTime.Text, dstatus);    // 添加日志信息到服务器
            else if (Mode.Equals("修改")) html = updateDaily(id, startTime.Text, content, consumed, endTime.Text, dstatus);
            if (!html.Equals("") && loginForm.floatMenu != null)   // 日志添加成功
            {
                loginForm.UpdateData();  // 刷新界面信息显示
                //loginForm.floatMenu.updateShowing();            
                this.Close();
            }
        }

        // 设置界面的显示模式
        public void setMode(string mode)
        {
            Mode = mode;
            button1.Text = mode;
            this.Text = mode + "日志";
        }

        public string id = "";
        // 设置日志信息
        public void setData(Data_Daily data)
        {
            id = data.id;
            textBox1.Text = data.work;
            if(showConsume) setHours(Tool.toFloat(data.consumed, 0));
            comboBox1.SelectedIndex = Tool.toInt(data.dstatus, 0) == 3 ? 0 : 1;    // 设置为对应的任务状态

            startTime.Text = data.createTime;
            endTime.Text = data.endTime;

            time1 = startTime.Text;
            time2 = endTime.Text;

            // 由指派任务自动生成的日志信息，禁止修改
            if (data.dtype.Equals("1"))
            {
                button1.Enabled = false;
                textBox1.Enabled = false;
            }
            label_info.Visible = (data.dtype.Equals("1"));
        }
        

        // 新建一个日志信息修改界面
        public static DailyForm Modify(Data_Daily data, bool show)
        {
            DailyForm form = new DailyForm();
            form.setMode("修改");
            if(show) form.Show();   // 先行初始化并显示界面

            form.setData(data);
            
            
            return form;
        }
        


        // 日志提交示例：
        // http://task.joymeng.com/daily.php

        //type            insert               
        //id                                   
        //uaccount        admin                
        //work            新增日志—11.02      
        //createTime      2016-05-13 10:38:00  
        //markday         2016-05-13           
        //dtype           0                    
        //consumed        2                    
        //isAchieve       1                    
        //endTime         2016-05-13 10:38:00  
        //dstatus         0                    
        //leadTime                             
        //tid                                  
        //submit          提交   

        // 修改日志信息
        public static string updateDaily(string id, String createTime, String content, String consumed, String endTime, String dstatus)
        {
            // 获取当前日期
            String now = Tool.TimeNow();  // "2016-5-13 13:53:00" 

            string leadTime = "0";
            //if(dstatus.Equals("0"))
            //{
            //    // 预期结束时间
            //    float needHours = Tool.toFloat(consumed);
            //    string end = Tool.parseDate(createTime).AddHours(needHours).ToString().Replace("/", "-");

            //    dstatus = (Tool.Date_cmp(end, now) > 0) ? "1" : "2";            // 当前为提前或超时完成
            //    leadTime = Tool.Sub_minite(end, now) + "";                      // 获取两个时间之间的差值
            //    if(leadTime.Equals("0")) dstatus = "0";                         // 准时完成
            //}

            //String isAchieve = dstatus.Equals("3") ? "0" : "1";                     // 状态3为进行中，其它0、1、2为完成状态
            String isAchieve = "1";
            string updateSql = "UPDATE zt_daily SET `work`='" + content + "',`createTime`='" + createTime + "',`consumed`='" + consumed + "',`isAchieve`='" + isAchieve + "',`endTime`='" + endTime + "', `dstatus`='" + dstatus + "', `leadTime`='" + leadTime + "' WHERE `id`='" + id + "'";
            string html = Tool.Execute(updateSql);

            return html;
        }

        // 添加日志
        public static string addDaily(String content, String createTime, String consumed, String endTime, String dstatus)
        {
            return dailyProcess("insert", "", content, createTime, consumed, endTime, dstatus);
        }

        // 添加日志
        public static string dailyProcess(String mode, string id, String content, String createTime, String consumed, String endTime, String dstatus)
        {
            //String createTime = DateTime.Now.ToString().Replace("/", "-");          // "2016-5-13 13:53:00"
            String markday = Tool.getDate(DateTime.Now);                     // "2016-5-13"
            //String isAchieve = dstatus.Equals("3") ? "0" : "1";            // 状态3为进行中，其它0、1、2为完成状态
            String isAchieve = "1";

            //string sql = newDailySql(loginForm.userName, content, createTime, markday, "0", consumed, isAchieve, endTime, dstatus, "0", "", "提交");
            //string html = Tool.Execute(sql);

            string html = postData(mode, id, loginForm.userName, content, createTime, markday, "0", consumed, isAchieve, endTime, dstatus, "0", "", "提交");
            return html;
        }

        private static string newDailySql(string uaccount, string work, string createTime, string markday, string dtype, string consumed, string isAchieve, string endTime, string dstatus, string leadTime, string tid, string submit)
        {
            string str1 = "INSERT INTO zt_daily(uaccount, work, createTime, markday, dtype, consumed, isAchieve, endTime, dstatus, leadTime, tid, submit)";
            string str2 = "VALUES('"+ uaccount + "', '" + work + "', '" + createTime + "', '" + markday + "', '" + dtype + "', '" + consumed + "', '" + isAchieve + "', '" + endTime + "', '" + dstatus + "', '" + leadTime + "', '" + tid + "', '" + submit + "')";
            string sql = str1 + str2;

            return sql;
        }

        // 提交信息接口
        public static string postData(string type, string id, string uaccount, string work, string createTime, string markday, string dtype, string consumed, string isAchieve, string endTime, string dstatus, string leadTime, string tid, string submit)
        {
            string url = "http://" + loginForm.serverIP + "/daily.php";
            string postData = "type=" + type + "&id=" + id + "&uaccount=" + uaccount + "&work=" + work + "&createTime=" + createTime + "&markday=" + markday + "&dtype=" + dtype + "&consumed=" + consumed + "&isAchieve=" + isAchieve + "&endTime=" + endTime + "&dstatus=" + dstatus + "&leadTime=" + leadTime + "&tid=" + tid + "&submit=" + submit;

            // 发送任务状态修改信息到服务器
            string html = HttpTool.GetHtml(url, postData, Method.POST);

            return html;
        }

        // 刷新,根据耗时设置预计结束时间
        private void pictureBox_refresh_Click(object sender, EventArgs e)
        {
            //int needHours = Tool.toInt(comboBox2.Text.Trim());
            //DateTime endingTime = DateTime.Now.AddHours(needHours);

            //textBox3.Text = endingTime.ToString().Replace("/", "-");          // "2016-5-13 13:53:00"
        }

        private int initSelectedIndex = 1;                  // 默认选中完成

        private bool init = true;
        // 界面初始设置
        private void DailyForm_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = initSelectedIndex;    // 任务状态选择

            if (startTime.Text.Equals("")) startTime.Text = Tool.TimeNow();
            if (endTime.Text.Equals("")) endTime.Text = Tool.TimeNow();

            time1 = startTime.Text;
            time2 = endTime.Text;

            for (int i = 0; i < 30; i++) comboBox_day.Items.Add(i);
            for (int i = 0; i < 24; i++) comboBox_hour.Items.Add(i);
            for (int i = 0; i < 60; i=i+1) comboBox_minute.Items.Add(i);

            // 设置为下拉选择列表
            comboBox_hour.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox_minute.DropDownStyle = ComboBoxStyle.DropDownList;

            comboBox_hour.SelectedIndex = 0;
            comboBox_minute.SelectedIndex = 0;

            //comboBox_day.Visible = false;
            //label6.Visible = false;

            showConsume = loginForm.settings.newDaily_showCosumePannel.Equals("1");
            panel_consume.Visible = showConsume;
            //刷新1.Visible = showConsume;
            //刷新2.Visible = showConsume;

            label_info.Visible = false;     // 此提示信息默认不可见


            // 为起始时间和结束时间各添加一个日期时间选择控件
            DateTimeChoser.AddTo(startTime);
            DateTimeChoser.AddTo(endTime);


            init = false;
        }

        private bool showConsume = false;   // 是否显示耗时控件


        // 获取消耗的时长
        private float toHours()
        {
            int day = Tool.toInt(comboBox_day.Text, 0);
            int hour = Tool.toInt(comboBox_hour.Text, 0);
            int minute = Tool.toInt(comboBox_minute.Text, 0);

            float Hours = 24 * day + hour + minute / 60f;
            return Hours;
        }

        // 根据消耗时长，设置对应显示
        private void setHours(float hours)
        {
            int day = (int)(hours/24);
            int hour = (int)(hours % 24);
            int minute = (int)(hours * 60 % 60);

            if (!comboBox_day.Text.Equals(day.ToString())) comboBox_day.Text = day.ToString();
            if (!comboBox_hour.Text.Equals(hour.ToString())) comboBox_hour.Text = hour.ToString();
            if (!comboBox_minute.Text.Equals(minute.ToString())) comboBox_minute.Text = minute.ToString();
        }

        private void DailyForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            FloatMenu.dailyForm = null;
            //if (Choser != null)
            //{
            //    Choser.Close();
            //    Choser = null;
            //}
        }

        private void 刷新1_Click(object sender, EventArgs e)
        {
            startTime.Text = Tool.TimeNow();
        }

        private void 刷新2_Click(object sender, EventArgs e)
        {
            endTime.Text = Tool.TimeNow();
        }

        int count = 0;

        // 开始时间或结束时间变动处理逻辑，耗时随之变动
        private void start_endTime_Changed()
        {
            try
            {
                float hours = (float)Tool.Sub_minite(endTime.Text, startTime.Text) / 60.0f;

                Tool.parseDate(startTime.Text);
                time1 = startTime.Text;
                Tool.parseDate(endTime.Text);
                time2 = endTime.Text;

                setHours(hours);
            }
            catch (Exception ex) 
            {
                startTime.Text = time1;
                endTime.Text = time2;
            }
        }

        // 耗时变动处理逻辑，结束时间随之变动
        private void consumed_Changed()
        {
            DateTime start = Tool.parseDate(startTime.Text);

            int day = Tool.toInt(comboBox_day.Text, 0);
            int hour = Tool.toInt(comboBox_hour.Text, 0);
            int minute = Tool.toInt(comboBox_minute.Text, 0);

            start = start.AddDays(day);
            start = start.AddHours(hour);
            start = start.AddMinutes(minute);

            string tmp = Tool.ToString(start);
            if (!endTime.Text.Equals(tmp)) endTime.Text = tmp;
        }

        private void start_endTime_TextChanged(object sender, EventArgs e)
        {
            if (!init && showConsume) timer1.Enabled = true;
        }

        private void consumed_TextChanged(object sender, EventArgs e)
        {
            if (!init && showConsume) consumed_Changed();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            start_endTime_Changed();
        }

        // 为日期时间输入框添加输入控件
        private void DateTime_MouseClick(object sender, MouseEventArgs e)
        {
            //TextBox textBox = (TextBox)sender;

            //// 创建一个日期时间选择控件
            //DateTimeChoser choser = new DateTimeChoser();

            //// 设置选中的日期时间
            //DateTime time = DateTime.Now;
            //try
            //{  
            //    time = Tool.parseDate(textBox.Text); 
            //}
            //catch(Exception ex){}
            //choser.setDateTime(time);  

            //// 为TextBox绑定日期时间输入控件
            //choser.showOn(textBox);
        }

        private void startTime_ControlRemoved(object sender, ControlEventArgs e)
        {
            MessageBox.Show("控件移除测试！");
        }
    }
}
